<template>
  <div
    class="page_body"
    v-loading.fullscreen.lock="loadingKey"
    :element-loading-text="loadingText"
  >
    <!-- 面包屑 -->
    <el-row>
      <el-col :span="24" class="page_box_top">
        <i class="el-icon-s-fold"></i>
        <el-breadcrumb separator="/" class="page_box_top_nav">
          <el-breadcrumb-item class="breadcrumb_active_item"
            >用户管理</el-breadcrumb-item
          >
          <el-breadcrumb-item>机构用户</el-breadcrumb-item>
        </el-breadcrumb>
      </el-col>
    </el-row>
    <el-row>
      <div class="organization_user_content">
        <!-- 搜索框 -->
        <el-row type="flex" justify="center">
          <el-col :span="6">
            <div class="organization_user_search">
              <el-input
                v-model="searchKey"
                placeholder="请输入"
                size="small"
              ></el-input>
              <el-button
                type="primary"
                size="small"
                style="margin-left: 5px"
                @click="searchFn()"
                >搜索</el-button
              >
            </div>
          </el-col>
        </el-row>
        <!-- 按钮栏 -->
        <el-row>
          <el-col :span="24">
            <div class="organization_user_top">
              <el-button size="mini" type="primary" @click="addFn()"
                >新增</el-button
              >
              <el-upload
                class="upload-demo"
                :action="actionUrl"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload"
                :headers="headers"
                :name="uploadName"
                style="margin-left: 10px"
              >
                <el-button size="mini" type="primary">导入用户</el-button>
              </el-upload>
              <el-button
                size="mini"
                type="primary"
                style="margin-left: 10px"
                @click="downloadTemplateFn()"
              >
                下载模板
              </el-button>
            </div>
          </el-col>
        </el-row>
        <!-- 数据列表 -->
        <div v-if="userListData != undefined && userListData.length > 0">
          <el-row>
            <el-col :span="24">
              <el-table
                :data="userListData"
                border
                size="mini"
                style="width: 100%"
              >
                <el-table-column
                  type="index"
                  label="序号"
                  width="50"
                  align="center"
                >
                </el-table-column>

                <el-table-column
                  prop="name"
                  label="机构名称"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="phone"
                  label="手机号码"
                  align="center"
                ></el-table-column>

                <el-table-column
                  prop="created_at"
                  label="创建时间"
                  align="center"
                ></el-table-column>

                <el-table-column label="操作" width="320" align="center">
                  <template slot-scope="scope">
                    <el-checkbox
                      size="mini"
                      :value="scope.row.is_test == '2' ? true : false"
                      @change="tableCheckChange($event, scope.row)"
                      style="margin-right: 10px"
                      >推荐机构</el-checkbox
                    >
                    <el-button
                      size="mini"
                      type="primary"
                      @click="detailFn(scope.$index, scope.row)"
                      >查看</el-button
                    >
                    <el-button
                      size="mini"
                      type="primary"
                      @click="editFn(scope.$index, scope.row)"
                      >编辑</el-button
                    >
                    <el-button
                      size="mini"
                      type="danger"
                      @click="deleteFn(scope.$index, scope.row)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="organization_user_pagination">
                <el-pagination
                  @size-change="listSizeChange"
                  @current-change="listCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="pageSizes"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="total"
                >
                </el-pagination>
              </div>
            </el-col>
          </el-row>
        </div>
        <el-row v-else>
          <el-empty description="暂无数据"></el-empty>
        </el-row>
      </div>
    </el-row>
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="dialogClose"
    >
      <el-row>
        <el-col :span="24">
          <el-form
            ref="submitFrom"
            :model="submitData"
            label-width="100px"
            :rules="rules"
            :disabled="dialogEditKey == 3"
          >
            <el-form-item label="机构名称" size="small" prop="name">
              <el-col :span="24">
                <el-input v-model="submitData.name" maxlength="20"></el-input>
              </el-col>
            </el-form-item>

            <el-form-item label="手机号" size="small" prop="phone">
              <el-col :span="24">
                <el-input
                  type="number"
                  v-model="submitData.phone"
                  maxlength="12"
                ></el-input>
              </el-col>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <el-row type="flex" justify="center">
        <el-col :span="24">
          <div
            class="organization_user_dialog_btn_box"
            v-if="dialogEditKey != 3"
          >
            <el-button
              size="small"
              type="primary"
              @click="dialogSubmitBtn()"
              style="margin-right: 30px"
              >确认</el-button
            >
            <el-button size="small" type="danger" @click="dialogClose()"
              >取消</el-button
            >
          </div>
          <div class="organization_user_dialog_btn_box" v-else>
            <el-button size="small" type="primary" @click="dialogClose()"
              >确认</el-button
            >
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>
<style src="../../assets/css/user/organizationUser.css" scoped></style>

<script>
export default {
  name: "OrganizationUser",
  components: {},
  data() {
    return {
      baseAPIUrl: this.$store.state.baseAPIUrl,
      actionUrl: this.$store.state.baseAPIUrl + "/admin/excel/importUserOg", // 上传路径
      uploadName: "excelfile",
      headers: {
        Authorization: this.$store.state.loginToken,
      }, // 上传用token
      userListData: [], // 用户列表
      currentPage: 1, // 当前页
      pageSizes: [10, 20, 50, 100], // 可选页容量
      pageSize: 10, // 当前页容量
      total: 0, // 总条数
      dialogTitle: "", // 弹窗标题
      dialogVisible: false, // 弹窗显示
      dialogEditId: "", // 编辑id
      dialogEditKey: 0, // 是否编辑
      submitData: {
        name: "",
        phone: "",
      }, // 弹框提交数据
      searchKey: "", // 搜索关键字
      rules: {
        name: [
          { required: true, message: "请输入机构名称", trigger: "change" },
        ],
        phone: [
          { required: true, validator: this.validatePhone, trigger: "change" },
        ],
      }, // 校验规则
      loadingKey: false,
      loadingText: "",
    };
  },
  created: function () {
    this.getListDataFn();
  },
  methods: {
    // 手机号校验
    validatePhone: function (rule, value, callback) {
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else {
        let telText =
          /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-9])\d{8}$/;
        if (!telText.test(value)) {
          callback(new Error("手机号格式不正确"));
        } else {
          callback();
        }
      }
    },
    // 搜索
    searchFn: function () {
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 获取列表数据
    getListDataFn: function () {
      let that = this;
      let url = "/admin/users/index";
      let data = {
        type: 2,
        page: this.currentPage,
        perPage: this.pageSize,
        keywords: this.searchKey,
      };
      that.loadingText = "加载中...";
      that.loadingKey = true;
      this.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.userListData = response.user_info;
            that.total = response.total_count;
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
    // 新增
    addFn: function () {
      let that = this;
      this.dialogTitle = "新增用户";
      this.dialogEditId = "";
      this.dialogEditKey = 2;
      this.submitData = {
        name: "",
        phone: "",
      };
      this.$nextTick(function () {
        that.dialogVisible = true;
        that.$refs.submitFrom.clearValidate();
      });
    },
    // 修改
    editFn: function (index, row) {
      this.dialogTitle = "编辑用户";
      this.dialogEditId = row.id;
      this.dialogEditKey = 1;
      this.submitData = {
        name: row.name,
        phone: row.phone,
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },
    // 查看用户
    detailFn: function (index, row) {
      this.dialogTitle = "查看用户";
      this.dialogEditId = row.id;
      this.dialogEditKey = 3;
      this.submitData = {
        name: row.name,
        phone: row.phone,
      };
      this.$nextTick(function () {
        this.dialogVisible = true;
      });
    },
    // 删除
    deleteFn: function (index, row) {
      let that = this;
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(() => {
        let url = "/admin/users/destroy";
        let data = {
          id: row.id,
        };
        that.loadingText = "处理中...";
        that.loadingKey = true;
        that.axios
          .post(url, data)
          .then((response) => {
            that.loadingKey = false;
            if (response.code == 0) {
              that.$message.success("删除成功");
              let next = that.currentPage - 1;
              if (that.userListData.length == 1) {
                that.currentPage = next >= 1 ? next : 1;
              }
              that.getListDataFn();
            } else {
              that.$message.error(response.msg);
            }
          })
          .catch(function (error) {
            that.loadingKey = false;
            console.log(error);
          });
      });
    },
    // 页容量改变
    listSizeChange: function (val) {
      this.currentPage = 1;
      this.pageSize = val;
      this.getListDataFn();
    },
    // 当前页改变
    listCurrentChange: function (val) {
      this.currentPage = val;
      this.getListDataFn();
    },
    // 关闭弹窗
    dialogClose: function () {
      this.dialogVisible = false;
    },
    // 弹窗提交按钮
    dialogSubmitBtn: function () {
      let that = this;
      let url = "";
      let data = {};
      if (this.dialogEditKey == 1) {
        url = "/admin/users/update";
        data = {
          id: this.dialogEditId,
          name: this.submitData.name,
          phone: this.submitData.phone,
        };
      } else {
        url = "/admin/users/createUserOg";
        data = {
          name: this.submitData.name,
          phone: this.submitData.phone,
        };
      }
      this.$refs.submitFrom.validate((valid) => {
        if (!valid) {
          return false;
        } else {
          that.loadingText = "处理中...";
          that.loadingKey = true;
          this.axios
            .post(url, data)
            .then((response) => {
              that.loadingKey = false;
              if (response.code == 0) {
                if (that.dialogEditKey == 1) {
                  that.$message.success("修改成功");
                } else {
                  that.$message.success("新增成功");
                }
                that.dialogClose();
                that.getListDataFn();
              } else {
                that.$message.error(response.msg);
              }
            })
            .catch(function (error) {
              that.loadingKey = false;
              console.log(error);
            });
        }
      });
    },
    // 上传成功钩子
    handleAvatarSuccess: function (res) {
      if (res.code == 1) {
        this.$message.error(res.msg);
      } else {
        this.$message.success("导入成功");
      }
      this.currentPage = 1;
      this.getListDataFn();
    },
    // 上传前钩子
    beforeAvatarUpload: function (file) {
      let type = file.name.indexOf(".xlsx");
      if (type == -1) {
        this.$message.error("上传xlsx文件");
        return false;
      }
      return true;
    },
    // 下载模板
    downloadTemplateFn: function () {
      const link = document.createElement("a");
      // 这里是将链接地址url转成blob地址，
      fetch(this.baseAPIUrl + "/download/userog_import_demo.xlsx")
        .then((res) => res.blob())
        .then((blob) => {
          link.href = URL.createObjectURL(blob);
          // 下载文件的名称及文件类型后缀
          link.download = "userog_import_demo.xlsx";
          document.body.appendChild(link);
          link.click();
          // 在资源下载完成后 清除 占用的缓存资源
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        });
    },
    // 开启勾选切换
    tableCheckChange: function (val, row) {
      let that = this;
      let url = "/admin/users/changeTestStatus";
      let data = {
        id: row.id,
      };
      data.is_test = val ? 2 : 1;
      that.loadingText = "处理中...";
      that.loadingKey = true;
      that.axios
        .post(url, data)
        .then((response) => {
          that.loadingKey = false;
          if (response.code == 0) {
            that.$message.success("操作成功");
            that.getListDataFn();
          } else {
            that.$message.error(response.msg);
          }
        })
        .catch(function (error) {
          that.loadingKey = false;
          console.log(error);
        });
    },
  },
};
</script>
